<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: tinlam
 * Date: 11/11/14
 * Time: 2:11 PM
 */

class User extends MY_Controller {

    var $_fgpassword = "";

    public function __construct()
    {
        parent::__construct();
        $this->layout->setLayout('frontend/index');
    }


    public function register(){
        $data = array();
        if (isset($_POST['submit']) and $_POST['submit'] == 'register'){

            $this->form_validation->set_rules('name', 'User name', 'required|min_length[8]|xss_clean|callback_check_username_registration');
            $this->form_validation->set_rules('email','Email', 'trim|required|valid_email');
            $this->form_validation->set_rules('gender','Gender', 'trim|required');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|xss_clean');
            $this->form_validation->set_rules('repassword', 'Confirm Password', 'required|matches[password]|xss_clean');
            $this->form_validation->set_rules('dob', 'Date of Birth', 'required|xss_clean');
            $this->form_validation->set_rules('idcard', 'Identification Number', 'required|numeric|xss_clean');
            $this->form_validation->set_rules('address1', 'Address', 'required|xss_clean');
            $this->form_validation->set_rules('fullname', 'Full Name', 'required|xss_clean');

            if($this->form_validation->run())
            {
                $data = array(
                'user_name'     => $this->input->post('name'),
                'full_name' =>$this->input->post('fullname'),
                'gender'    => $this->input->post('gender'),
                'date_of_birth' => $this->input->post('dob'),
                'address'  => $this->input->post('address1')." ". $this->input->post('address2'),
                'tel' => $this->input->post('tel'),
                'email'    => $this->input->post('email'),
                'id_card' => $this->input->post('idcard'),
                'register_date' => gmdate('Y-m-d'),
                'password' => md5($this->input->post('password')),
                'usergroup_id' => '2',
                );
                if($this->muser->create($data))
                {
                    redirect();
                }
            }
        }
        elseif(isset($_POST['submit']) and $_POST['submit'] == 'login'){
            $this->form_validation->set_rules('username_login', 'User name', 'required|min_length[8]|xss_clean');
            $this->form_validation->set_rules('password_login', 'Password', 'required|min_length[6]|xss_clean|callback_check_database');
            if($this->form_validation->run())
            {
                $session_data = $this->session->userdata('logged_in');
                $data['username'] = $session_data['username'];
                $data['fullname'] = $session_data['fullname'];
                $data['is_logged_in'] = true;
                redirect();
            }
        }
        $this->layout->view('frontend/login', $data);
    }

    public function viewOrder($id){
        $data['invoices'] = $this->minvoice->getInvoiceById($id);
        $data['invoices_detail'] = $this->minvoicedetail->getInvoiceDetailById($id);
        $this->layout->view('frontend/invoice_detail', $data);
    }

    public function userInformation(){
        $session_data = $this->session->userdata('logged_in');
        $data['username'] = $session_data['username'];
        $user_information = $this->muser->get_user_information($session_data['username']);
        foreach($user_information as $row){
            $data['user_id'] = $row->user_id;
            $data['user_name'] = $row->user_name;
            $data['full_name'] = $row->full_name;
            $data['gender'] = $row->gender;
            $data['date_of_birth'] = $row->date_of_birth;
            $data['address'] = $row->address;
            $data['tel'] = $row->tel;
            $data['email'] = $row->email;
            $data['id_card'] = $row->id_card;
            $data['register_date'] = $row->register_date;
            $usergroup_id = $row->usergroup_id;
        }
        $usergroup_information = $this->musergroup->get_usergroup_information($usergroup_id);
        foreach($usergroup_information as $row){
            $data['usergroup_id'] = $row->usergroup_id;
            $data['usergroup_name'] = $row->usergroup_name;
            $data['discount'] = $row->discount;
            $data['url_image'] = $row->url_image;
        }
        $uid = $this->session->userdata('logged_in')['uid'];
        $data['invoices'] = $this->minvoice->getInvoiceByUserId($uid);
        $this->layout->view('frontend/user_information', $data);
    }

    public function editInformation()
    {
        $session_data = $this->session->userdata('logged_in');
        $data['username'] = $session_data['username'];
        $user_information = $this->muser->get_user_information($session_data['username']);
        foreach($user_information as $row){
            $user_name = $row->user_name;
            $data['user_id'] = $row->user_id;
            $data['user_name'] = $user_name;
            $data['full_name'] = $row->full_name;
            $password = $row->password;
            $data['gender'] = $row->gender;
            $data['date_of_birth'] = $row->date_of_birth;
            $data['address'] = $row->address;
            $data['tel'] = $row->tel;
            $data['email'] = $row->email;
            $data['id_card'] = $row->id_card;
            $data['register_date'] = $row->register_date;
            $usergroup_id = $row->usergroup_id;
        }
        if (isset($_POST['submit']) and $_POST['submit'] == 'update'){
            $this->form_validation->set_rules('email','Email', 'trim|required|valid_email');
            $this->form_validation->set_rules('gender','Gender', 'trim|required');
            $this->form_validation->set_rules('dob', 'Date of Birth', 'required|xss_clean');
            $this->form_validation->set_rules('idcard', 'Identification Number', 'required|numeric|xss_clean');
            $this->form_validation->set_rules('address1', 'Address', 'required|xss_clean');
            $this->form_validation->set_rules('fullname', 'Full Name', 'required|xss_clean');
            if($this->form_validation->run())
            {
                $user_data = array(
                    'full_name' =>$this->input->post('fullname'),
                    'gender'    => $this->input->post('gender'),
                    'date_of_birth' => $this->input->post('dob'),
                    'address'  => $this->input->post('address1')." ". $this->input->post('address2'),
                    'tel' => $this->input->post('tel'),
                    'email'    => $this->input->post('email'),
                    'id_card' => $this->input->post('idcard'),
                    'register_date' => gmdate('Y-m-d'),
                );
                $this->muser->updateUser($user_data, $data['user_id']);
                $sess_array = array(
                    'username' => $data['user_name'],
                    'fullname' => $this->input->post('fullname'),
                );
                $this->session->set_userdata('logged_in', $sess_array);
                redirect("frontend/user/userInformation");
            }
        }
        elseif (isset($_POST['submit']) and $_POST['submit'] == 'change_password'){
            $this->form_validation->set_rules('old_password', 'Old Password', 'required|min_length[6]|xss_clean|callback_check_password');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|xss_clean');
            $this->form_validation->set_rules('repassword', 'Confirm Password', 'required|matches[password]|xss_clean');
            if($this->form_validation->run()){
                $password_data = array("password" => md5($this->input->post("password")));
                $this->muser->updateUser($password_data, $data['user_id']);
                redirect("frontend/user/userInformation");
            }
        }
        $this->layout->view('frontend/edit_information', $data);
    }
    public function logout(){
        $this->session->sess_destroy();
        $this->session->unset_userdata('is_logged_in');
        redirect();
    }

    public function forget(){
        $data['check'] = false;
        $this->form_validation->set_rules('username_login', 'User name', 'required|min_length[8]|xss_clean|callback_check_username');
        if($this->form_validation->run()==FALSE){
            $this->layout->view("frontend/forget_password",$data);
        }
        else {
            $result = $this->muser->check_username($this->input->post('username_login'));
            foreach($result as $row){
                $id = $row->user_id;
                $username = $row->user_name;
                $email = $row->email;
                $fullname = $row->full_name;
            }
            $message = "";
            $password = create_random_string(10);
            $reset = array(
                "password" => md5($password),
            );
            $this->muser->updateUser($reset, $id);
            $message = "<b>".$fullname. "</b>, your password at Petshop has been reset. You may log in using the password listed below. <br/><br/>";
            $message .= "Username : <b>". $username . "</b><br/>";
            $message .= "Password: <b>" . $password. "</b><br/><br/>";
            $message .= "Thanks. <br/><br/><br/>";
            $message .= "<b>Petshop </b><br/>";
            $message .= "Phone: 0906371118";

            $mail = array(
                "to_receiver" => $email,
                "message" => $message,
                "subject" => "Petshop Password Reset"
            );
            $this->email->config($mail);
            $this->email->sendmail();
            $data['check'] = true;
        }
        $this->layout->view('frontend/forget_password', $data);
    }


    public function check_username_registration($username){
        $count=$this->db->where(array('user_name'=>$username))->from('user')->count_all_results();
        if($count!=0){
            $this->form_validation->set_message('_username','%s is not available');
            return FALSE;
        }
        return TRUE;
    }

    function check_username($username){
        $result = $this->muser->check_username($username);
        if($result){
            return TRUE;
        }
        else{
            $this->form_validation->set_message("check_username","Username is not available, please try again !<br/> For more information, please call: 090637118");
            return FALSE;
        }
    }
    function check_password($password)
    {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('username_login');

        //query the database
        $result = $this->muser->login($username, $password);
        if($result){
            return TRUE;
        }
        else{
            $this->form_validation->set_message('check_password', 'Old password is not correct');
            return false;
        }
    }
        function check_database($password)
    {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('username_login');

        //query the database
        $result = $this->muser->login($username, $password);

        if($result)
        {
            $sess_array = array();
            foreach($result as $row)
            {
                $sess_array = array(
                    'username' => $row->user_name,
                    'fullname' => $row->full_name,
                    'uid' => $row->user_id,
                    'usergroup_id' => $row->usergroup_id
                );
                $this->session->set_userdata('logged_in', $sess_array);
            }
            return TRUE;
        }
        else
        {
            $this->form_validation->set_message('check_database', 'username or password is invalid');
            return false;
        }
    }


}